package bll

import (
	"context"
	"encoding/json"
	"fmt"
	"manager/lib/trace_log"
	SignalPo "manager/model/signal"
	"manager/store/redis"
	"manager/utils"
	"proto/dto"
	"time"
)

const (
	SignalCmd      = "cmd"
	SignalToggle   = "toggle"
	SignalSettings = "settings"
)

var DelayCommand = &delayCommand{}

// DelayCommand 延迟命令，当设备不在线的时候命令又必须下达给设备的场景下，在设备上线的时候下发这些指令给设备
type delayCommand struct {
}

// AddCommand 添加命令
func (d *delayCommand) AddCommand(sn string, cmd string, data interface{}) (err error) {
	defer utils.ExceptionCatch()
	key := fmt.Sprintf("delay_command:%v", sn)
	// 添加到redis
	redis.KV.AddHash(context.Background(), key, cmd, data)

	// 设置过期时间
	redis.KV.Expire(context.Background(), redis.CacheHash, key, time.Hour*24*90)
	return
}

// RemoveCommand 移除命令
func (d *delayCommand) RemoveCommand(sn string) (err error) {
	defer utils.ExceptionCatch()
	// 删除所有命令
	key := fmt.Sprintf("delay_command:%v", sn)
	redis.KV.HDelAll(context.Background(), key)
	return
}

// ExecCommand 执行命令
func (d *delayCommand) ExecCommand(sn string) (err error) {
	defer utils.ExceptionCatch()
	values, _ := redis.KV.HGetAll(context.Background(), fmt.Sprintf("delay_command:%v", sn))
	for cmd, data := range values {
		switch cmd {
		case SignalCmd:
		case SignalToggle:
			out := &dto.SwitchRequest{}
			if err = json.Unmarshal([]byte(data), out); err != nil {
				continue
			}

			bikeId, _err := CacheBike.GetBikeIdBySn(sn)
			if _err != nil {
				continue
			}

			err = SignalV2.SendToggleToDevice(&SignalPo.ToggleReq{
				EbikeId:       bikeId,
				SwitchRequest: *out,
			})
			if err != nil {
				trace_log.DebugLogger(sn, "ExecCommand err:%v", err)
				return err
			}
		case SignalSettings:
		}
	}

	err = d.RemoveCommand(sn)
	if err != nil {
		trace_log.DebugLogger(sn, "ExecCommand RemoveCommand err:%v", err)
	}
	return
}
